define([
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
	"UtilDir/loading",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang",
    ],function(Util, Tool, SelectOrg, SearchBlock, Loading){

	var getBoundaryController = function () {
		return getServer() + "/boundary";
	};

	var getFxBuildingResistanceAbilityEvaluateController = function(){
		return getServer() + "/fxBuildingResistanceAbilityEvaluate";
	};

	/**
	 * 页面初始化
	 */
	var init = function(){
		var t = setInterval(function () {
			if (T.PolygonTool) {
				clearInterval(t);
				initSearchBlock();
				queryBtnBind();
				initProvinceSelect("山东省", "日照市", "");
				initYearDate();
				initMap();
				formValidator();
			}
		}, 10);
	};
	var initProvinceSelect = function (Province, City, Area) {
		var html = "";
		$("#citySelect").append(html);
		$("#areaSelect").append(html);
		$.ajax({
			url: getServer() +"/divisions/root/subdivisions",
			contentType: "application/json",
			type: "get",
			success: function (data) {
				var ProvinceCode;
				$.each(data, function (idx, item) {
					if (item.divisionName == Province) {
						ProvinceCode = item.divisionCode;
						var divisionId = item.divisionId;
						var htmlCity = '';
						if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
							$("#citySelect").append("<option value='" + ProvinceCode + "' exid='" + divisionId + "'>" + Province + "</option>");
							$('#citySelect').val(ProvinceCode);
							var htmlArea = '';
							$.ajax({
								url: getServer() +"/divisions/" + divisionId + "/subdivisions",
								contentType: "application/json",
								type: "get",
								success: function (data) {
									var AreaCode;
									$.each(data, function (idx, item) {
										if (item.divisionName == Area) AreaCode = item.divisionCode;
										htmlArea += "<option value='" + item.divisionCode + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
									});
									$("#areaSelect").append(htmlArea);
									$('#areaSelect').val(AreaCode);
									// 列表
									//queryFxBuildingsData();
								}
							});

						} else {
							$.ajax({
								url: getServer() +"/divisions/" + divisionId + "/subdivisions",
								contentType: "application/json",
								type: "get",
								success: function (data) {
									debugger;
									var CityCode;
									$.each(data, function (idx, item) {
										if (item.divisionName == City) {
											CityCode = item.divisionCode;
											var divisionId = item.divisionId;
											var htmlArea = '';
											$.ajax({
												url: getServer() +"/divisions/" + divisionId + "/subdivisions",
												contentType: "application/json",
												type: "get",
												success: function (data) {
													var AreaCode;
													$.each(data, function (idx, item) {
														if (item.divisionName == Area) AreaCode = item.divisionCode;
														htmlArea += "<option value='" + item.divisionCode + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
													});
													$("#areaSelect").append(htmlArea);
													$('#areaSelect').val(AreaCode);
												}
											});
										}
										htmlCity += "<option value='" + item.divisionCode + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
									});
									$("#citySelect").append(htmlCity);
									$('#citySelect').val(CityCode);
								}
							});
						}
					}
					html += "<option value='" + item.divisionCode + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
				});
				$("#provinceSelect").append(html);
				$('#provinceSelect').val(ProvinceCode);
			}
		});
		$("#provinceSelect").change(function () {
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#citySelect option").remove();
			$("#citySelect").append(html);
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			//if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
			if ($(this).val() == "110000" || $(this).val() == "120000" || $(this).val() == "310000" || $(this).val() == "500000") {
				$("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).find("option:selected").text() + "</option>");
				return;
			}
			$.ajax({
				url: getServer() +"/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionCode + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#citySelect").append(html);
				}
			});
		});
		$("#citySelect").change(function () {
			if ($(this).val() == "") return;
			var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			$.ajax({
				url: getServer() +"/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionCode + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#areaSelect").append(html);
				}
			});
		});
	};
	var initYearDate = function() {
		$("#yearCondition").datetimepicker({
			//设置使用语言：cn是自定义的中文版本，还可以扩展其他语言版本
			language : "cn",
			//输出格式化
			format : 'yyyy-mm-dd',
			//直接选择‘今天’
			todayBtn : true,
			//设置最精确的时间选择视图
			minView : 'month',
			//高亮当天日期
			todayHighlight : true,
			//选择完毕后自动关闭
			autoclose : true
		});
	};
	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){
        $("#btnSearch").click(function () {
			if($("#searchForm").valid()){
				queryFxBuildingsData();
			}
        });
        $("#btnReset").click(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
			$("#citySelect option").remove();
			$("#citySelect").append(html);
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
			initProvinceSelect("山东省", "日照市", "");
//			$("#yearCondition").val("");
//			$("#buildingNameCondition").val("");
//	        $("#structureTypeSelect").val("");
		});
		$("#up-map-div").click(function () {
			$("#searchButton").css("background-position", "125px 47px");
			polygonTool.open();
		});
	}
	var formValidator = function(){
		$("#searchForm").validate({
			rules : {
				provinceSelect : {
					required : true,
				},
				citySelect : {
					required : true,
				}
			},
			messages : {
				provinceSelect : {
					required : "省不允许为空!",
				},
				citySelect : {
					required : "市不允许为空!",
				}
			}
		});
	};
	var queryFxBuildingsData = function(province, city, area, coords_str) {
		tdMap.clearOverLays();
		var province = province || $("#provinceSelect").val() || "", city = city || $("#citySelect").val() || "", area = area || $("#areaSelect").val() || "";
		var intensity = $("#fx-REQAD-intensity-checkbox-div input[type=radio]:checked").val();
		if (intensity == "") {alert("[基础设防烈度]功能暂未实现"); return;}
		loading.show();
		var formData = {province: province, city: city, area: area, earthquakeIntensity: intensity};
		$.ajax({
			url: getFxBuildingResistanceAbilityEvaluateController() + "/fxBuildingResistanceAbilityDistrict",
			data: formData,
			type: "POST",
			success: function (result) {
				console.log(result);
				//loading.close();
				if (result && result.data) {
					global_areaIsFinished = {};
					var area2e = result.data, district, p, c, a, value;
					for (var key in area2e) {
						district = key.split("-");
						value = area2e[key]; p = district[0]; c = district[1]; a = district[2];
						global_areaIsFinished[district] = false;
						renderDistrictByEvaluation(value, p, c, a, district);
					}
				} else {
					loading.close();
					if (!coords_str) Util.alert("查询数据为空!");
				}
			}
		});
	};
	var renderDistrictByEvaluation = function (evaluation, province, city, area, district) {
		var formData = {province: province, city: city, area: area};
		$.ajax({
			url: getBoundaryController() + "/getSingleAreaBoundary",
			type: "POST",
			data: formData,
			success: function (coords) {
				//console.log("coords:", coords);
				global_areaIsFinished[district] = true;
				if (coords && coords != "") {
					coords = coords[area];
					var _coords = coords.split("|");
					for (let k = 0; k < _coords.length; k++) {
						var lonlats = _coords[k].split(";"), lonlat, lon = 0, lat = 0, points = [];
						for (var i = 0;i < lonlats.length;i++) {
							lonlat = lonlats[i].split(",");
							lon = parseFloat(lonlat[0]); lat = parseFloat(lonlat[1]);
							points.push(new T.LngLat(lon, lat));
						}
						global_points = global_points.concat(points);
						var color = getPolygonColorByValue(evaluation);
						console.log(evaluation, "color: ", color);
						var areaPolygon = new T.Polygon(points, {
							color: "#0000ff",
							weight: 1,
							opacity: 0.5,
							fillColor: color,
							fillOpacity: 0.5
						});
						tdMap.addOverLay(areaPolygon);
					}
					taskIsFinish(global_areaIsFinished) && (loading.close(), tdMap.setViewport(global_points));
				} else {
					loading.close();
					Util.alert("【" + province + city + area + "】无边界数据!");
				}
			}
		});
	};
	var getPolygonColorByValue = function (value) {
		return (value <= 0.3) ? rank_color["0"] : ((value > 0.3 && value <= 0.5) ? rank_color["1"] : (value > 0.5 && value <= 0.7) ? rank_color["2"] : (value > 0.7 ? rank_color["3"] : ""));
	};
	var taskIsFinish = function (obj) {
		for (var _key in obj) if (!obj[_key]) return false;
		return true;
	};

	//var rank_color = {"0": "#F65314", "1": "#7CBB00", "2": "#00A1F1", "3": "#FFBB00"};
	var rank_color = {"0": "#63BF36", "1": "#F9F400", "2": "#F09C42", "3": "#E33539"};
	var loading = Loading({text : "正在查询数据..."});
	var tdMap, polygonTool, global_points = [], global_areaIsFinished = {};
	var initMap = function () {
		var mapH = document.body.clientHeight - $(".pd-search-container").height() - 10;
		$("#fx-REQAD-mapDiv").height(mapH);

		var vec_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/d9ffc071-50dd-4780-a617-673d17921e22/wmts?service=wmts&request=gettile&version=1.0.0&layer=vec&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var cva_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/13f8b69d-98dc-4276-bbf0-9c4c372acabc/wmts?service=wmts&request=gettile&version=1.0.0&layer=cva&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var config = {
			projection: 'EPSG:4326',
			minZoom: 4,
			layers: [vec_layer, cva_layer]
		};
		tdMap = new T.Map('fx-REQAD-mapDiv', config), zoom = 4;
		tdMap.centerAndZoom(new T.LngLat(106.34766, 34.37971), zoom);

		polygonTool = new T.PolygonTool(tdMap);
		polygonTool.addEventListener("draw", endRectDraw);
	};

	var endRectDraw = function (params) {
		tdMap.clearOverLays();
		queryFxBuildingsDataByRect(params);
		polygonTool.close();
		$("#searchButton").css("background-position", "125px 0");
	};
	var queryFxBuildingsDataByRect = function (obj) {
		console.log(obj);
		tdMap.removeOverLay(obj.currentPolygon);
		var coords_str = "";
		var lnglats = obj.currentLnglats, lnglat, xD = [], yD = [];
		for (let i = 0; i < lnglats.length; i++) {
			lnglat = lnglats[i];
			xD.push(lnglat.lat);
			yD.push(lnglat.lng);
			coords_str += (lnglat.lat + "," + lnglat.lng + ";");
		}
		coords_str = coords_str.substring(0, coords_str.length - 1);
		console.log(coords_str);
		loading.show();
		$.ajax({
			url: getBoundaryController() + "/isPolygonsIntersect?coords=" + coords_str,
			type: "get",
			success: function (data) {
				console.log(data);
				if (data && data.length) {
					var p_c_a;
					for (let i = 0; i < data.length; i++) {
						p_c_a = data[i].split("-");
						p_c_a[1] = specialCityName(p_c_a[1]);
						queryFxBuildingsData(p_c_a[0], p_c_a[1], p_c_a[2], coords_str);
					}
				} else {
					loading.close();
					Util.alert("查询无数据!");
				}
			},
			error: function (xhr, textStatus, errorThrown) {
				loading.close();
				Util.alert("查询数据失败, 错误信息:" + xhr.statusText);
			}
		});
	};
	var specialCityName = function (name) {
		(name == "北京城区") && (name = "北京市");
		(name == "天津城区") && (name = "天津市");
		(name == "上海城区") && (name = "上海市");
		(name == "重庆城区") && (name = "重庆市");
		return name;
	};
	var specialCityName2 = function (name) {
		(name == "北京市") && (name = "北京城区");
		(name == "天津市") && (name = "天津城区");
		(name == "上海市") && (name = "上海城区");
		(name == "重庆市") && (name = "重庆城区");
		return name;
	}

	return {
		init:init
	};
});
